package com.template.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class TemplateHandler {

	private Configuration configuration = null;

	public TemplateHandler(String tempPath) {
		try {
			configuration = new freemarker.template.Configuration();
			configuration.setDirectoryForTemplateLoading(new File(tempPath));
			configuration.setObjectWrapper(new DefaultObjectWrapper());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void execute(String tempName, String savePath,
			Map<String, Object> param) throws Exception {
		Template template = configuration.getTemplate(tempName, "UTF-8");
		template.setEncoding("UTF-8");
		File file = new File(savePath);
		if(!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(file);
		Writer writer = new OutputStreamWriter(fos, "UTF-8");
		template.process(param, writer);
		writer.flush();
		writer.close();
		fos.close();
	}
}
